﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Twittit.Business
{
    public class TagService
    {
        private Twittit.DataAccess.DatabaseEntities data;
        private static TagService instance;

        private TagService()
        {
            data = new Twittit.DataAccess.DatabaseEntities();
        }

        public static TagService getInstance()
        {
            if (instance == null)
                instance = new TagService();
            return instance;
        }

        // Retrieve Tag by content, create if not found
        public Twittit.DataAccess.Tag getTag(String content)
        {
            try
            {
                return data.Tag.Where(t => t.tag1 == content.ToLower().Substring(0, content.Length > 63 ? 63 : content.Length)).First();
            }
            catch(Exception)
            {
                Twittit.DataAccess.Tag t = new Twittit.DataAccess.Tag();
                t.tag1 = content.ToLower().Substring(0, content.Length > 63 ? 63 : content.Length);
                data.Tag.AddObject(t);
                data.SaveChanges();
                return t;
            }
        }

        public List<DataAccess.Tag> getTags(String value = null)
        {
            if(value != null)
                return data.Tag.Where(t=> t.tag1.StartsWith(value)).OrderBy(t => t.tag1).ToList();
                return data.Tag.OrderBy(t => t.tag1).ToList();            
        }
    }
}
